import React, { useEffect, useState } from 'react';
import { BellOutlined, LogoutOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Badge, Dropdown, Menu, Tooltip } from 'antd';
import { useHistory, Link } from 'react-router-dom';

const AvatarDropdown: React.FC<any> = (props) => {
  const { currentUser = {}, location, dispatch } = props;
  const history = useHistory();
  const [unreadMessageNum, setUnreadMessageNum] = useState<number>(0);

  // useEffect(() => {
  //   if (currentUser._id) {
  //     loadData();
  //   }
  // }, [currentUser]);

  const onMenuClick = (event: {
    key: React.Key;
    keyPath: React.Key[];
    item: React.ReactInstance;
    domEvent: React.MouseEvent<HTMLElement>;
  }) => {
    const { key } = event;

    const keyPathMap = {
      accountsettings: '/accountsettings',
      message: '/account/message',
    };

    if (key === 'logout') {
      if (dispatch) {
        dispatch({
          type: 'login/logout',
        });
      }
      return;
    }

    // const path = keyPathMap[key];
    // if (location?.pathname !== path) {
    //   history.push(path);
    // }
  };

  /**
   * 下拉菜单
   */
  const menuHeaderDropdown = (
    <Menu selectedKeys={[]}>
      <Menu.Item key='/accountsettings'>
        <UserOutlined />
        个人中心
      </Menu.Item>
      <Menu.Item key='/message'>
        <BellOutlined />
        消息中心
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key='/logout'>
        <span style={{ color: 'red' }}>
          <LogoutOutlined />
          退出登录
        </span>
      </Menu.Item>
    </Menu>
  );

  return !currentUser?._id ? (
    <Dropdown dropdownRender={() => menuHeaderDropdown}>
      <div className='hover:cursor-pointer'>
        <Badge count={unreadMessageNum}>
          {currentUser.head_img ? (
            <Avatar src={currentUser.head_img} />
          ) : (
            <Avatar>无</Avatar>
          )}
        </Badge>
      </div>
    </Dropdown>
  ) : (
    <Tooltip title='登录后，享用全部功能' placement='bottomLeft' defaultVisible>
      <Link to='/login'>
        <Avatar icon={<UserOutlined />} />
      </Link>
    </Tooltip>
  );
};

export default AvatarDropdown;
